package com.english.controller;

import com.english.controller.admin.AdminBaseController;
import com.english.entity.User;
import com.english.service.WechatPayService;
import com.english.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 微信支付控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/payment")
@CrossOrigin(origins = "*", allowCredentials = "false", maxAge = 3600)
public class WechatPayController extends AdminBaseController {

    @Autowired
    private WechatPayService wechatPayService;

    /**
     * 创建支付订单
     */
    @PostMapping("/create")
    public R<Map<String, Object>> createPayment(
            @RequestHeader("Authorization") String token,
            @RequestParam BigDecimal amount,
            @RequestParam(required = false, defaultValue = "课时充值") String description) {
        try {
            // 解析token获取用户ID
            Long userId = getUserIdFromToken(token);
            
            if (userId == null) {
                return R.error("用户认证失败");
            }
            
            // 验证用户是否为学生
            User user = userMapper.selectById(userId);
            if (user == null || user.getRole() != 0) {
                return R.error("只有学生才能充值");
            }
            
            // 验证金额
            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return R.error("支付金额无效");
            }
            
            // 创建支付订单
            Map<String, Object> paymentParams = wechatPayService.createPayment(userId, amount, description);
            
            return R.success("创建支付订单成功", paymentParams);
            
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            return R.error("创建支付订单失败: " + e.getMessage());
        }
    }

    /**
     * 测试微信支付接口（绕过认证）
     */
    @PostMapping("/test-create")
    public R<Map<String, Object>> testCreatePayment(
            @RequestParam BigDecimal amount,
            @RequestParam(required = false, defaultValue = "测试支付") String description) {
        try {
            // 使用固定的用户ID 7 进行测试
            Long userId = 7L;
            
            Map<String, Object> result = wechatPayService.createPayment(userId, amount, description);
            return R.success("创建支付订单成功", result);
            
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            return R.error("创建支付订单失败: " + e.getMessage());
        }
    }

    /**
     * 微信支付回调通知
     */
    @PostMapping("/notify")
    public String paymentNotify(HttpServletRequest request) {
        try {
            // 读取回调数据
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            String notifyData = sb.toString();
            log.info("收到微信支付回调: {}", notifyData);
            
            // 处理回调
            boolean success = wechatPayService.handlePaymentNotify(notifyData);
            
            if (success) {
                return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            } else {
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>";
            }
            
        } catch (IOException e) {
            log.error("处理支付回调失败", e);
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[系统错误]]></return_msg></xml>";
        }
    }

    /**
     * 查询订单状态
     */
    @GetMapping("/query/{orderNo}")
    public R<Map<String, Object>> queryOrder(@PathVariable String orderNo) {
        try {
            Map<String, Object> orderInfo = wechatPayService.queryOrder(orderNo);
            return R.success("查询成功", orderInfo);
        } catch (Exception e) {
            log.error("查询订单失败", e);
            return R.error("查询订单失败: " + e.getMessage());
        }
    }

    /**
     * 申请退款
     */
    @PostMapping("/refund")
    public R<String> refund(
            @RequestParam String orderNo,
            @RequestParam BigDecimal refundAmount,
            @RequestParam(required = false, defaultValue = "用户申请退款") String reason) {
        try {
            boolean success = wechatPayService.refund(orderNo, refundAmount, reason);
            
            if (success) {
                return R.success("退款申请成功");
            } else {
                return R.error("退款申请失败");
            }
            
        } catch (Exception e) {
            log.error("申请退款失败", e);
            return R.error("申请退款失败: " + e.getMessage());
        }
    }
} 